<!-- eslint-disable vue/multi-word-component-names -->
 <template>
  <div>
    <div style="margin-bottom: 5px; text-align: center;">
      <el-button 
        type="primary" 
        :icon="Refresh" 
        circle 
        style="margin-left: 5px;"
        @click="resetParam()"
      />
      
      <el-button 
        type="primary" 
        :icon="Plus" 
        circle 
        style="margin-left: 5px;" 
        @click="add()"
      />
      
      <el-button 
        type="danger" 
        :icon="Delete" 
        circle 
        style="margin-left: 5px;" 
        @click="delHandle(null)"
        :disabled="delBtnStatus"
      />
    </div>
    
    <el-table 
      :data="tableData" 
      ref="multipleTableRef" 
      tooltip-effect="dark" 
      border 
      style="width: 100%;" 
      stripe
      @selection-change="handleSelectionChange" 
      row-key="id" 
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column type="selection" width="55" />
      
      <el-table-column prop="name" label="名称" sortable width="180" />
      
      <el-table-column prop="code" label="权限编码" sortable width="180" />
      
      <el-table-column prop="icon3" label="图标">
        <template #default="scope">
          <component :is="scope.row.icon3" v-if="scope.row.icon3" class="icon"/>
        </template>
      </el-table-column>
      
      <el-table-column prop="type" label="类型">
        <template #default="scope">
          <el-tag size="small" v-if="scope.row.type === 0" type="primary">目录</el-tag>
          <el-tag size="small" v-else-if="scope.row.type === 1" type="success">菜单</el-tag>
          <el-tag size="small" v-else-if="scope.row.type === 2" type="info">按钮</el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="path" label="菜单URL" />
      
      <el-table-column prop="component" label="菜单组件" width="200" />
      
      <el-table-column prop="orderNum" label="排序号" />
      
      <el-table-column prop="status" label="状态" width="150">
        <template #default="scope">
          <el-switch 
            :model-value="scope.row.status == 1" 
            active-color="#13ce66" 
            inactive-color="#ff4949" 
            active-text="正常"
            inactive-text="禁用" 
            @change="modStatus(scope.row.id)"
          />
        </template>
      </el-table-column>
      
      <el-table-column prop="operate" label="操作" fixed="right" width="120">
        <template #default="scope">
          <el-button 
            type="primary" 
            :icon="Edit" 
            circle 
            @click="mod(scope.row)"
            style="margin-left: 5px;"
          />
          
          <el-button 
            type="danger" 
            :icon="Delete" 
            circle 
            style="margin-left: 5px;"
            @click="delHandle(scope.row.id)"
          />
        </template>
      </el-table-column>
    </el-table>
    
    <el-dialog 
      v-model="centerDialogVisible" 
      title="菜单表单" 
      width="600px"
    >
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="formRef" 
        label-width="100px"
      >
        <el-form-item label="上级菜单" prop="parentId" label-width="100">
          <el-select v-model="form.parentId" placeholder="请选择上级菜单">
            <el-option label="父级菜单" value="0" key="0" />
            
            <template v-for="item in tableData" :key="item.id">
              <el-option :label="item.name" :value="item.id" />
              
              <template v-for="child in item.children" :key="child.id">
                <el-option :label="child.name" :value="child.id">
                  <span>{{ "- " + child.name }}</span>
                </el-option>
              </template>
            </template>
          </el-select>
        </el-form-item>
        
        <el-form-item label="菜单名称" prop="name" label-width="100px">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        
        <el-form-item label="权限编码" prop="code" label-width="100px">
          <el-input v-model="form.code" autocomplete="off" />
        </el-form-item>
        
        <el-form-item 
          label="图标" 
          v-if="form.type != 2" 
          label-width="100px" 
          prop="icon3"
        >
          <el-select clearable v-model="form.icon3" placeholder="请选择" style="width: 100%">
            <el-option 
              v-for="item in iconData" 
              :key="item.name" 
              :label="item.name" 
              :value="item.value"
            >
              <component :is="item.value" class="icon"/>{{ item.name }}
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="类型" prop="type" label-width="100px">
          <el-radio-group v-model="form.type">
            <el-radio :label="0">目录</el-radio>
            <el-radio :label="1">菜单</el-radio>
            <el-radio :label="2">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item 
          label="菜单URL" 
          prop="path" 
          label-width="100px" 
          v-if="form.type == 1"
        >
          <el-input v-model="form.path" autocomplete="off" />
        </el-form-item>
        
        <el-form-item 
          label="菜单组件" 
          prop="component" 
          label-width="100px" 
          v-if="form.type == 1"
        >
          <el-input v-model="form.component" autocomplete="off" />
        </el-form-item>
        
        <el-form-item label="排序号" prop="orderNum" label-width="100px">
          <el-input-number 
            v-model="form.orderNum" 
            :min="1" 
            label="排序号"
          >
            1
          </el-input-number>
        </el-form-item>
        
        <el-form-item 
          label="按钮" 
          prop="perm" 
          label-width="100px" 
          v-if="form.type == 1"
        >
          <el-checkbox-group v-model="perm" size="small">
            <el-checkbox 
              v-for="item in permData" 
              :key="item.id" 
              :label="item.name" 
              border
            />
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="save">确定</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="danger" @click="centerDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
// eslint-disable-next-line vue/multi-word-component-names
import { ref, reactive, onMounted } from 'vue'
import { 
  Refresh, 
  Plus, 
  Delete, 
  Edit 
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/axios/index'

// refs
const multipleTableRef = ref()
const formRef = ref()

// 数据响应式
const tableData = ref([])
const iconData = ref([])
const perm = ref([])
const delBtnStatus = ref(true)

const permData = [
  { id: 1, name: "新增" },
  { id: 2, name: "修改" },
  { id: 3, name: "删除" },
  { id: 4, name: "查询" },
  { id: 5, name: "控制状态" },
  { id: 6, name: "导入" },
  { id: 7, name: "导出" }
]

const multipleSelection = ref([])
const centerDialogVisible = ref(false)

const form = reactive({ 
  parentId: "", 
  name: "", 
  code: "", 
  type: 0, 
  orderNum: "", 
  status: 1, 
  component: "", 
  path: "", 
  icon: "" ,
  icon3:""
})

const rules = {
  parentId: [
    { required: true, message: "请选择上级菜单", trigger: "blur" },
  ],
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入权限编码", trigger: "blur" }],
  type: [{ required: true, message: "请选择状态", trigger: "blur" }],
  icon3: [{ required: true, message: "请选择图标", trigger: "blur" }],
  orderNum: [
    { required: true, message: "请填入排序号", trigger: "blur" },
  ],
  component: [
    { required: true, message: "请填组件", trigger: "blur" },
  ],
  path: [
    { required: true, message: "请填入路径", trigger: "blur" },
  ],
  status: [{ required: true, message: "请选择状态", trigger: "blur" }],
}

// 方法
const handleSelectionChange = (val) => {
  console.log(val)
  multipleSelection.value = val
  delBtnStatus.value = val.length == 0
}

const delHandle = (id) => {
  console.log(id)
  var ids = []
  if (id) {
    ids.push(id)
  } else {
    multipleSelection.value.forEach(row => {
      ids.push(row.id)
    })
  }
  console.log(ids)
  
  ElMessageBox.confirm('此操作将永久删除菜单数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    api.post('/menu/deleteBatch', ids, {
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    }).then(res => {
      console.log(res)
      if (res.code == 200) {
        ElMessage({
          showClose: true,
          message: '恭喜你，操作成功',
          type: 'success',
          onClose: () => {
            loadPost()
          }
        })
      } else {
        ElMessage({
          showClose: true,
          message: res.msg,
          type: 'error'
        })
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

const resetForm = () => {
  Object.assign(form, { 
    parentId: "", 
    name: "", 
    code: "", 
    type: 0, 
    orderNum: "", 
    status: 1, 
    component: "", 
    path: "", 
    icon: "" 
  })
  perm.value = []
}

const modStatus = (id) => {
  api.post("/menu/modStatus/" + id)
    
    .then((res) => {
      console.log(res)
      if (res.code == 200) {
        loadPost()
      } else {
        ElMessage({
          message: "操作失败！",
          type: "error",
        })
      }
    })
}

const loadPost = () => {
  api.get("/menu/tree").then((res) => {
    tableData.value = res.data
    console.log(res.data)
  })
}

const resetParam = () => {
  loadPost()
}

const add = () => {
  // 重置表单
  resetForm()
  
  // 显示对话框
  centerDialogVisible.value = true
  
  console.log(form)
}

const mod = (row) => {
  api.get('/menu/info/' + row.id).then((res) => {
    Object.assign(form, res.data)
  })
  centerDialogVisible.value = true
}

const save = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (form.id) {
        doMod()
      } else {
        doSave()
      }
    } else {
      ElMessage({
        message: "校验失败",
        type: "error"
      })
    }
  })
}

const doSave = () => {
  api.post("/menu/save", form).then((res) => {
    console.log(res)
    if (res.code == 200) {
      console.log(res.id)
      //存储返回的数据
      if (perm.value.length > 0) {
        doHandleSave(res.id)
      } else {
        centerDialogVisible.value = false
        loadPost()
        resetForm()
        ElMessage({
          message: res.msg,
          type: "success"
        })
      }
    } else {
      ElMessage({
        message: res.msg,
        type: "error"
      })
    }
  })
}

const doHandleSave = (id) => {
  console.log(perm.value)
  api.post("/menu/saveHandle/" + perm.value + "/" + id)
    .then((res) => {
      console.log(res)
      if (res.code == 200) {
        centerDialogVisible.value = false
        loadPost()
        resetForm()
        ElMessage({
          message: "操作成功！",
          type: "success"
        })
      } else {
        ElMessage({
          message: res.msg,
          type: "error"
        })
      }
    })
}

const doMod = () => {
  api.post("/menu/update", form).then((res) => {
    console.log(res)
    if (res.code == 200) {
      //存储返回的数据
      console.log(form.id)
      
      if (perm.value.length > 0) {
        doHandleSave(form.id)
      } else {
        centerDialogVisible.value = false
        loadPost()
        resetForm()
        ElMessage({
          message: "修改成功！",
          type: "success"
        })
      }
    } else {
      ElMessage({
        message: res.msg,
        type: "success"
      })
    }
  })
}

const getIcon = () => {
  api.post("/dict/listPage", {
    pageSize: 1000,
    pageNum: 1,
    param: {
      type: 'icon3',
    }
  }).then((res) => {
    if (res.code == 200) {
      iconData.value = res.data
    } else {
      ElMessage({
        message: '数据查询失败',
        type: "error"
      })
    }
  })
}

// 生命周期
onMounted(() => {
  getIcon()
  loadPost()
})
</script>

<style scoped>
/* 如果需要自定义样式可以在这里添加 */
.icon {
    width: 25px;
    height: 25px;
}
</style>